package com.burgeon.backend.SHOP.service.Impl;

import com.burgeon.backend.SHOP.entity.CouponType;
import com.burgeon.backend.SHOP.entity.Goods;
import com.burgeon.backend.SHOP.entity.IndexCoupon;
import com.burgeon.backend.SHOP.mappers.AppCouponMapper;
import com.burgeon.backend.SHOP.mappers.GoodsMapper;
import com.burgeon.backend.SHOP.rest.CreateAppCoupon;
import com.burgeon.backend.SHOP.rest.GetUserShopCoupon;
import com.burgeon.backend.SHOP.service.AppCouponService;
import com.burgeon.backend.SHOP.service.AppTemplateService;
import com.burgeon.backend.SHOP.service.ex.ErrorDataExceptionApp;
import com.burgeon.backend.entity.Coupon;
import com.burgeon.backend.entity.Info;
import com.burgeon.backend.mappers.AccountMapper;
import com.burgeon.backend.mappers.CouponRestrictMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class AppCouponServiceImpl implements AppCouponService {

    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private AppCouponMapper appCouponMapper;
    @Autowired
    private AppTemplateService appTemplateService;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private CouponRestrictMapper couponRestrictMapper;

    @Override
    public List<Coupon> getErpCoupon(String phone, String token) {

        Info info = GetInfo(token);
        GetUserShopCoupon getUserShopCoupon = new GetUserShopCoupon(info.getUrl(), info.getAccount(), info.getPassword());
        try {
            return getUserShopCoupon.getData(phone);
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("小程序优惠券");
        }

        return null;
    }

    @Override
    public void createIndexCoupon(String cid, String uid, String phone, String openid, String token) throws ErrorDataExceptionApp {

        IndexCoupon indexCoupon = appCouponMapper.findIndexCouponById(cid);
        String scene = "1";//没错
        List<String> goodsCode = new ArrayList<String>();
        List<String> storeCode = new ArrayList<String>();
        if (null != indexCoupon.getTid()) {
            CouponType couponType = appCouponMapper.findCouponTypeById(indexCoupon.getTid());
           if (couponType!=null){
               indexCoupon.setName(couponType.getName());
               indexCoupon.setOriginal(couponType.getOriginal());
               indexCoupon.setPrice(couponType.getMoney());
               scene = couponType.getScene();
               if (couponType.getRestrictStore().equals("Y")){
                   storeCode = couponRestrictMapper.getCouponTypeRestrictStore(couponType.getId());
               }
               if (couponType.getRestrictProduct().equals("Y")){
                   goodsCode = couponRestrictMapper.getCouponTypeRestrictProduct(couponType.getId());
               }
           }

        }

        String code = create_nonce_str().replace("-", "").trim().substring(22, 32);
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DATE, Integer.parseInt(indexCoupon.getDate()));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat sssdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat ssdf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm");//消息模板使用
        Date date = new Date();
        String sTime = sdf.format(date);
        //  String ssTime = sdf.format(date);
        String creation = ssdf.format(date);

        date = c.getTime();

        String eTime = sdf.format(date);
        // String seTime = sdf.format(date);
        Coupon couponData = new Coupon();
        couponData.setCode(code);
        couponData.setMoney(indexCoupon.getPrice());
        couponData.setOriginal(indexCoupon.getOriginal());
        couponData.setDateend(eTime);
        couponData.setDatebeg(sTime);
        couponData.setVipCode(phone);
        couponData.setType("VOU5");
        couponData.setScene(scene);
        couponData.setName(indexCoupon.getName());
        couponData.setAccount(token);
        couponData.setToken(token);
        couponData.setCreation(creation);
        String source = "新人领券";
        couponData.setSource(source);

        appCouponMapper.addCoupon(couponData);

        if (!"1".equals(scene)) {
            try {
                Info info = GetInfo(token);
                CreateAppCoupon createAppCoupon = new CreateAppCoupon(info.getUrl(), info.getAccount(), info.getPassword());


                String objid = createAppCoupon.getData(code, indexCoupon.getPrice(), phone,
                        indexCoupon.getOriginal(), sTime, eTime,
                        goodsCode,storeCode);

            } catch (Exception e) {
                e.printStackTrace();
                throw new ErrorDataExceptionApp("出现错误,稍后重试");
            }
        }

        appCouponMapper.createIndexCouponRecord(cid, uid, token);
        //发送消息
        Coupon coupon = new Coupon();
        coupon.setName("满" + indexCoupon.getOriginal() + "元减" + indexCoupon.getPrice() + "优惠券");
        coupon.setDateend(creation);
        coupon.setCreation(creation);
        coupon.setVipCode(phone);
        appTemplateService.SendExchangeCoupon(coupon, phone, openid, token);
    }

    @Override
    public List<IndexCoupon> getIndexCoupon(String uid, String token) {
        List<IndexCoupon> indexCoupons = appCouponMapper.showIndexCoupon(token);
        for (IndexCoupon indexCoupon : indexCoupons) {
            if (null != indexCoupon.getTid()) {
                CouponType couponType = appCouponMapper.findCouponTypeById(indexCoupon.getTid());
                indexCoupon.setName(couponType.getName());
                indexCoupon.setOriginal(couponType.getOriginal());
                indexCoupon.setPrice(couponType.getMoney());
            }


            if (null == uid || null == appCouponMapper.showIndexCouponRecord(uid, indexCoupon.getId(), token)) {
                indexCoupon.setUse("N");
            } else {
                indexCoupon.setUse("Y");
            }
        }
        return indexCoupons;
    }

    @Override
    public List<Coupon> getVipShopCoupon(String phone, String token) {
        List<Coupon> coupons = appCouponMapper.findCouponByPhone(phone, token);
        ArrayList<Coupon> data = new ArrayList();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date date = new Date();
        int nowTime = Integer.parseInt(sdf.format(date));
        for (Coupon coupon : coupons) {
            int endTime = Integer.parseInt(coupon.getDateend());
            if (endTime >= nowTime
                    && !"Y".equals(coupon.getUse())
                    && !"2".equals(coupon.getScene())
            ) {
                if (coupon.getScene() == null) {
                    coupon.setScene("3");
                }
                if (coupon.getUse() == null) {
                    coupon.setUse("N");
                }
                data.add(coupon);
            }
        }

       /* Info info = GetInfo(token);
        GetUserShopCoupon getUserShopCoupon = new GetUserShopCoupon(info.getUrl(), info.getAccount(), info.getPassword());
        try {
            return getUserShopCoupon.getData(phone);
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("小程序优惠券");
        }*/

        return data;
    }

    @Override
    public List<Coupon> getUserCoupon(String[] gids, String phone, String price, String token) {


        List<Coupon> coupons = appCouponMapper.findCouponByPhone(phone, token);
        ArrayList<Coupon> data = new ArrayList();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date date = new Date();
        int nowTime = Integer.parseInt(sdf.format(date));
        System.err.println("gids=" + Arrays.toString(gids));
        System.err.println(price);
        if (gids == null) {
            System.err.println("null");
            for (Coupon coupon : coupons) {
                int endTime = Integer.parseInt(coupon.getDateend());
                if (endTime >= nowTime && !"Y".equals(coupon.getUse())
                        && coupon.getOriginal() != null
                        && Integer.parseInt(coupon.getOriginal()) <= Integer.parseInt(price)

                ) {
                    data.add(coupon);
                }
            }
            return data;
        }
        //String[] arr = new String[]{"4", "10", "8"};
        List<Goods> goodsList = new ArrayList<>();
        for (String s : gids) {
            Goods goods = goodsMapper.getGoodsById(s);
            goodsList.add(goods);
        }

        for (Coupon coupon : coupons) {
            int endTime = Integer.parseInt(coupon.getDateend());
            if (endTime >= nowTime && !"Y".equals(coupon.getUse())
                    && coupon.getOriginal() != null
                    && Integer.parseInt(coupon.getOriginal()) <= Integer.parseInt(price)
                    && verificationCoupon(coupon, goodsList)
            ) {
                data.add(coupon);
            }
        }
        //判断优惠券是否限制
        //判断商品是否满足购物券限制

        /*Info info = GetInfo(token);
        UseCoupon useCoupon = new UseCoupon(info.getUrl(), info.getAccount(), info.getPassword());
        try {
            return useCoupon.getData(phone,price);
        } catch (Exception e) {
            e.printStackTrace();
        }*/

        System.err.println(data);
        return data;
    }

    @Override
    public Coupon getCouponDetails(String token, String code) {
        return appCouponMapper.getCouponDetails(token,code);
    }

    private boolean verificationCoupon(Coupon coupon, List<Goods> goodsList) {
        System.err.println("coupon=" + coupon);

        boolean row = false;
        if (coupon.getTypeid() != null) {
            CouponType couponType = appCouponMapper.findCouponTypeById(coupon.getTypeid());
            System.err.println(couponType);
            if (null == couponType) {
                return false;
            }

            if (!"2".equals(couponType.getScene())) {
                System.err.println("******************************");
                //判断是否满足条件
                if ("Y".equals(couponType.getRestrictBrand())) {
                    List<String> couponTypeRestrictBrand = couponRestrictMapper.getCouponTypeRestrictBrand(couponType.getId());
                    System.err.println(couponTypeRestrictBrand);
                    for (String s : couponTypeRestrictBrand) {
                        for (Goods goods : goodsList) {
                            if (s.equals(goods.getBrand())) {
                                return true;
                            }
                        }
                    }
                }

                if ("Y".equals(couponType.getRestrictClass())) {
                    List<String> couponTypeRestrictClass = couponRestrictMapper.getCouponTypeRestrictClass(couponType.getId());
                    System.err.println(couponTypeRestrictClass);

                    for (String s : couponTypeRestrictClass) {
                        for (Goods goods : goodsList) {
                            if (s.equals(goods.getClassifyItemId())) {
                                System.err.println(goods.getClassifyItemId());
                                return true;
                            }
                        }
                    }
                }

                if (!"Y".equals(couponType.getRestrictBrand())
                        && !"Y".equals(couponType.getRestrictClass())) {
                    return true;
                }

            }
        } else {
            row = true;
        }

        return row;
    }

    private Info GetInfo(String token) {
        return accountMapper.GetTokenData(token);
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }
}
